﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace NL.Advanced
{
    public class PERFORMANCE : MonoBehaviour
    {

        public float Performace;

        public bool FPSPrechecking = false;

        public float FPS_Weak = 20f;
        // Start is called before the first frame update


        //开启自动性能监听..
        public bool AutoDetectable = false;

        private void Start()
        {
            LOG.Show(gameObject, () =>
            {
                return $"Health={Performace}";
            });
        }
        private void Update()
        {
            if (!AutoDetectable) return;

            if (FPSPrechecking) return;


            if (SYS.FPS < FPS_Weak)
            {
                StartCoroutine(_DetectRunner(30, 30, w =>
                {
                    if (Performace < 30)
                        WeakCount++;

                    if (Performace > 80)
                        WeakCount = 0;

                    if (WeakCount > 5)
                    {
                        _DoPerformaceWeak();
                        WeakCount = 0;
                    }
                }));
            }

        }
        int WeakCount = 0;
        public float DetectDuaration = 0.3f;
        IEnumerator _DetectRunner(int count, int top, Action<float> on)
        {
            LOG.Add($"[PERFORMANCE._DetectRunner].............");
            // FPS检测....
            FPSPrechecking = true;

            yield return 0;
            List<float> records = new List<float>();

            top = Math.Max(10, top);
            Performace = 100;
            int nn = count;
            while (nn-- > 0)
            {
                if (SYS.FPS < top)
                {
                    float a = SYS.FPS / (1f * top);
                    Performace -= (1 - a) * (1 - a) * (100f / count);
                }
                yield return new WaitForSeconds(DetectDuaration);
            }


            yield return 0;
            FPSPrechecking = false;

            on?.Invoke(Performace);
            LOG.Add($"[PERFORMANCE._DetectRunner]:Performace={Performace}");

        }
        void _DoPerformaceWeak()
        {
            _ONWeak?.Invoke(Performace);
        }

        public void Detect(int count, int fpsref, Action<float> on)
        {
            StopAllCoroutines();

            StartCoroutine(_DetectRunner(count, fpsref, on));
        }

        public PERFORMANCE WaitDetecting(int count, int top, Action<float> on)
        {
            StartCoroutine(_DetectRunner(count, top, on));
            return this;
        }
        Action<float> _ONWeak;
        public PERFORMANCE WaitWeak(Action<float> on)
        {
            _ONWeak = on; return this;
        }
    }
}

